package com.ds.api.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import sun.misc.BASE64Decoder;

public class FtpUploadUtil {      

    public   FTPClient ftp;      
    /**  
     *   
     * @param path 上传到ftp服务器哪个路径下     
     * @param addr 地址  
     * @param port 端口号  
     * @param username 用户名  
     * @param password 密码  
     * @return  
     * @throws Exception  
     */    
    public   boolean connect(String path,String addr,int port,String username,String password) throws Exception {      
        boolean result = false;      
        ftp = new FTPClient();      
        int reply;      
        ftp.connect(addr,port);      
        ftp.login(username,password);      
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);      
        reply = ftp.getReplyCode();      
        if (!FTPReply.isPositiveCompletion(reply)) {      
            ftp.disconnect();      
            return result;      
        }      
        if (!ftp.changeWorkingDirectory(path)) {// 如果不能进入dir下，说明此目录不存在！  

            if (!ftp.makeDirectory(path)) {  

                //                System.out.println("创建文件目录【"+path+"】 失败！");  
            }  
        }    
        result = true;      
        return result;      
    }      
    /**  
     *   
     * @param file 上传的文件或文件夹  
     * @throws Exception  
     */    
    public  void upload(File file) throws Exception{
        try{
            if(file.isDirectory()){           
                ftp.makeDirectory(file.getName());                
                ftp.changeWorkingDirectory(file.getName());      
                String[] files = file.list();             
                for (int i = 0; i < files.length; i++) {      
                    File file1 = new File(file.getPath()+"\\"+files[i] );      
                    if(file1.isDirectory()){      
                        upload(file1);      
                        ftp.changeToParentDirectory();      
                    }else{                    
                        File file2 = new File(file.getPath()+"\\"+files[i]);      
                        FileInputStream input = new FileInputStream(file2);      
                        ftp.storeFile(file2.getName(), input);      
                        input.close();                            
                    }                 
                }      
            }else{      
                File file2 = new File(file.getPath());      
                FileInputStream input = new FileInputStream(file2);      
                ftp.storeFile(file2.getName(), input);      
                input.close(); 
            }  
            ftp.logout(); 
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally  
        {  
            if (ftp.isConnected())  
            {  
                try  
                {  
                    ftp.disconnect();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();
                }  
            }  
        }  
    }      

    /** 
     * Description: 从FTP服务器下载文件 
     * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保（cuihongbao@d-heaven.com）创建 
     * @param url FTP服务器hostname 
     * @param port FTP服务器端口 
     * @param username FTP登录账号 
     * @param password FTP登录密码 
     * @param remotePath FTP服务器上的相对路径 
     * @param fileName 要下载的文件名 
     * @param localPath 下载后保存到本地的路径 
     * @return boolean
     */  
    public static boolean downloadFile(String url, int port, String username, String password, String remotePath,  
            String fileName, String localPath)  
    {  
        boolean success = false;  
        FTPClient ftp = new FTPClient();  
        try  
        {  
            int reply;  
            // 连接FTP服务器  
            if (port > -1)  
            {  
                ftp.connect(url, port);  
            }  
            else  
            {  
                ftp.connect(url);  
            }  

            ftp.login(username, password);//登录  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply))  
            {  
                ftp.disconnect();  
                return success;  
            }  
            ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
            FTPFile[] fs = ftp.listFiles();  
            for (FTPFile ff : fs)  
            {  
                if (ff.getName().equals(fileName))  
                {  
                    File localFile = new File(localPath + "/" + ff.getName());  

                    OutputStream is = new FileOutputStream(localFile);  
                    ftp.retrieveFile(ff.getName(), is);  
                    is.close();  
                }  
            }  

            ftp.logout();  
            success = true;  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();
        }  
        finally  
        {  
            if (ftp.isConnected())  
            {  
                try  
                {  
                    ftp.disconnect();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();
                }  
            }  
        }  
        return success;  
    }
    /** 
     * <删除FTP上的文件> 
     * <远程删除FTP服务器上的录音文件> 
     * @param url FTP服务器IP地址 
     * @param port FTP服务器端口 
     * @param username FTP服务器登录名 
     * @param password FTP服务器密码 
     * @param remotePath 远程文件路径 
     * @param fileName 待删除的文件名 
     * @return boolean
     */  
    public static boolean deleteFtpFile(String url, int port, String username, String password, String remotePath,  
            String fileName)  
    {  
        boolean success = false;  
        FTPClient ftp = new FTPClient();  
        try  
        {  
            int reply;  

            // 连接FTP服务器  
            if (port > -1)  
            {  
                ftp.connect(url, port);  
            }  
            else  
            {  
                ftp.connect(url);  
            }  

            // 登录  
            ftp.login(username, password);  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply))  
            {  
                ftp.disconnect();  
                return success;  
            }  

            // 转移到FTP服务器目录  
            ftp.changeWorkingDirectory(remotePath);  
            success = ftp.deleteFile(remotePath + "/" + fileName);  
            ftp.logout();  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();
            success = false;  
        }  
        finally  
        {  
            if (ftp.isConnected())  
            {  
                try  
                {  
                    ftp.disconnect();  
                }  
                catch (Exception e)  
                {  
                    e.printStackTrace();
                }  
            }  
        }  
        return success;  
    }  

    public static boolean uploadBypath(String path){
        boolean b=true;
        try{
            FtpUploadUtil t = new FtpUploadUtil();    
            t.connect("\\appimg", "192.168.170.11", 21, "ucan11", "ucan11");    
            File file = new File(path);    
            t.upload(file);  

        }catch(Exception ex){
            b=false;
            ex.printStackTrace();
        }
        return b;
    }

    public static void main(String[] args) throws Exception{    
        FtpUploadUtil t = new FtpUploadUtil();    
        t.connect("\\appimg", "192.168.170.11", 21, "ucan11", "ucan11");    
        File file = new File("E:\\img\\3.jpg");    
        t.upload(file); 


    }    

    /**
     * 将接收的字符串转换成图片保存
     * @param imgStr 二进制流转换的字符串
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return
     */
    public static File saveToImgByStr(String imgStr,String imgPath,String imgName){
        File file=null;
        if(imgStr != null && imgStr.length() > 0){
            try {
                // 将字符串转换成二进制，用于显示图片
                // 将上面生成的图片格式字符串 imgStr，还原成图片显示
                byte[] imgByte =imgStr.getBytes();
                InputStream in = new ByteArrayInputStream(imgByte);
                file=new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等
                if (!file.exists()) { 
                    file.createNewFile();
                }
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = in.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            }
        }
        return file;
    }

    /**
     * 字符串转二进制
     * @param str 要转换的字符串
     * @return 转换后的二进制数组
     */
    public static byte[] hex2byte(String str) { // 字符串转二进制
        if (str == null)
            return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1)
            return null;
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer
                        .decode("0X" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }


    public static File GenerateImage(String imgStr,String filepath)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        BASE64Decoder decoder = new BASE64Decoder();
        File  file=null;
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            String imgFilePath = filepath;//新生成的图片  
            //生成jpeg图片  
            file=new File(imgFilePath);//可以是任何图片格式.jpg,.png等
            if (!file.exists()) { 
                file.createNewFile();
            }
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return file;  
        }   
        catch (Exception e)   
        {  
            e.printStackTrace();
            return null;  
        }  
    }


}  